package com.uyayo.oms.ucenter.controller;

import com.uyayo.framework.message.enums.ResultMsgEnum;
import com.uyayo.framework.web.annotation.GetRequestInfo;
import com.uyayo.framework.common.annotation.MethodName;
import com.uyayo.framework.common.exception.EmailMultipleException;
import com.uyayo.framework.common.exception.PhoneMultipleException;
import com.uyayo.framework.common.exception.UserMultipleException;
import com.uyayo.framework.message.model.Result;
import com.uyayo.framework.pagehelper.pojo.PageBean;
import com.uyayo.framework.pagehelper.pojo.PageResult;
import com.uyayo.framework.web.model.RequestInfo;
import com.uyayo.oms.system.biz.ParamBiz;
import com.uyayo.oms.ucenter.vo.MemberVO;
import com.uyayo.system.authority.entity.SysUser;
import com.uyayo.ucenter.entity.Member;
import com.uyayo.ucenter.entity.MemberState;
import com.uyayo.ucenter.model.MemberCondition;
import com.uyayo.ucenter.service.MemberService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.dozer.DozerBeanMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;


/**
 * 
 * Title: MemberController
 * Description:会员信息管理的控制器
 * Company: www.uyayo.com
 *
 * @author 优雅哟.胡逢君
 * @date 2015-4-13下午4:03:35
 * @version 1.0
 */
@Controller
@RequestMapping("/oms/ucenter/member")
public class MemberController {

	private final MemberService memberService;

	private final ParamBiz paramBiz;

	private  final MessageSource messageSource;

	private final DozerBeanMapper dozerBeanMapper;

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	public MemberController(ParamBiz paramBiz, MemberService memberService, MessageSource messageSource, DozerBeanMapper dozerBeanMapper) {
		this.paramBiz = paramBiz;
		this.memberService = memberService;
		this.messageSource = messageSource;
		this.dozerBeanMapper = dozerBeanMapper;
	}

	@RequestMapping(value="index",method=RequestMethod.GET)
	@MethodName(value="客户中心->会员管理")
	@RequiresPermissions("oms:ucenter:member:index")
	public String index() throws Exception {
		return paramBiz.getManagerTemplatesPrefix()+"ucenter/member/index";
	}
	
	@ResponseBody
	@RequestMapping(value="query",method=RequestMethod.GET)
	@MethodName(value="客户中心->会员管理->查询列表",type=2)
	@RequiresPermissions("oms:ucenter:member:query")
	public PageResult<Member> selectServer(@RequestParam(value = "offset",required = false, defaultValue = "1") Integer start, //第多少行之后开始
										   @RequestParam(value = "limit", required = false, defaultValue = "10") Integer pageSize,
										   String sort, String order, HttpServletRequest request, MemberCondition memberCondition) throws Exception {
		PageBean<Member> pageBean=new PageBean<>();
		try {
			pageBean.setPageCurrent((start / pageSize) + 1);
			pageBean.setPageSize(pageSize);
			pageBean.setOrderField(sort);
			pageBean.setOrderDirection(order);
			pageBean = memberService.selectMemberByPaging(pageBean,memberCondition);
		} catch (Exception e) {
			String message = messageSource.getMessage(ResultMsgEnum.INTERNAL_SERVER_ERROR.getKey(),new Object[]{}, request.getLocale());
			logger.error(message,e);
		}
		PageResult<Member> pageResult = new PageResult<>();
		pageResult.setRows(pageBean.getList());
		pageResult.setTotal(pageBean.getTotalCount());
		return pageResult;
		
	}
	
	/**
	 * 进入添加页面
	 * @param modelAndView ModelAndView
	 * @return ModelAndView
	 */
	@RequestMapping(value = "add", method = RequestMethod.GET)
	@RequiresPermissions("oms:ucenter:member:create")
	public ModelAndView add(ModelAndView modelAndView) {
		
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"ucenter/member/add");
		return modelAndView;
	}
	
	/**
	 * 新建一个服务器记录
	 */
	@ResponseBody
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@RequiresPermissions("oms:ucenter:member:create")
	@MethodName(value="客户中心->会员管理->保存",type=2)
	synchronized public Result add(HttpServletRequest request, @Validated MemberVO memberVO , @GetRequestInfo RequestInfo requestInfo, Errors errors) {
		try {
			if (errors.hasErrors()) {
				return Result.errorAndMsg(errors.getFieldError().getDefaultMessage());
		    }
			Subject subject = SecurityUtils.getSubject();
			SysUser sysUser = (SysUser) subject.getPrincipal();
			Member member = dozerBeanMapper.map(memberVO,Member.class);
			member.setCreateTime(new Date());
			member.setCreateBy(sysUser.getLoginname());
			MemberState memberState = new MemberState();
			memberState.setCreateTime(new Date());
			memberState.setCreateBy(sysUser.getLoginname());
			memberState.setLoginCount(0);
			memberState.setRegisterDevice(1);
			memberState.setRegisterIp(requestInfo.getRequestIp());
			memberState.setRegisterDomain(requestInfo.getDomainName());
			memberService.saveMember(member,memberState);
		}catch (UserMultipleException e){
			String message = messageSource.getMessage(ResultMsgEnum.USER_EXIST.getKey(),new Object[]{}, request.getLocale());
			logger.info(message,e.getMessage());
			return Result.error(ResultMsgEnum.USER_EXIST.code(),message);
		} catch (PhoneMultipleException e){
			String message = messageSource.getMessage(ResultMsgEnum.PHONE_MULTIPLE.getKey(),new Object[]{}, request.getLocale());
			logger.info(message,e.getMessage());
			return Result.error(ResultMsgEnum.CODE_MULTIPLE.code(),message);
		}  catch (EmailMultipleException e){
			String message = messageSource.getMessage(ResultMsgEnum.EMAIL_MULTIPLE.getKey(),new Object[]{}, request.getLocale());
			logger.info(message,e.getMessage());
			return Result.error(ResultMsgEnum.CODE_MULTIPLE.code(),message);
		}  catch (Exception e) {
			String message = messageSource.getMessage(ResultMsgEnum.INTERNAL_SERVER_ERROR.getKey(),new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.error(ResultMsgEnum.INTERNAL_SERVER_ERROR.code(),message);
		}
		String message = messageSource.getMessage(ResultMsgEnum.SAVE_SUCCESS.getKey(),new Object[]{}, request.getLocale());
		return Result.success(ResultMsgEnum.SAVE_SUCCESS.code(),message);
	}
	
	/**
	 * 进入服务器记录查看页面
	 */
	@RequestMapping(value = "view", method = RequestMethod.GET)
	@MethodName(value="客户中心->会员管理->查看",type=2)
	@RequiresPermissions("oms:ucenter:member:view")
	public ModelAndView show(ModelAndView modelAndView,HttpServletRequest request,Long id) {
		Member member = new Member();
		try {
			member = memberService.getMemberById(id);
		} catch (Exception e) {
			String message = messageSource.getMessage(ResultMsgEnum.INTERNAL_SERVER_ERROR.getKey(),new Object[]{}, request.getLocale());
			logger.error(message,e);
		}
		modelAndView.addObject("member",member);
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"ucenter/member/view");
		return modelAndView;
	}

	/**
	 * 进入角色修改页面
	 */
	@RequestMapping(value = "update", method = RequestMethod.GET)
	@RequiresPermissions("oms:ucenter:member:update")
	public ModelAndView update(ModelAndView modelAndView,HttpServletRequest request,Long id) {
		Member member = new Member();
		try {
			member = memberService.getMemberById(id);
		} catch (Exception e) {
			String message = messageSource.getMessage(ResultMsgEnum.INTERNAL_SERVER_ERROR.getKey(),new Object[]{}, request.getLocale());
			logger.error(message,e);
		}
		modelAndView.addObject("member",member);
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"ucenter/member/edit");
		return modelAndView;
	}
	
	/**
	 * 修改一个服务器记录
	 */
	@ResponseBody
	@RequestMapping(value = "update", method = RequestMethod.POST)
	@RequiresPermissions("oms:ucenter:member:update")
	@MethodName(value="客户中心->会员管理->修改",type=2)
	synchronized public Result update(HttpServletRequest request,@Validated MemberVO memberVO , Errors errors) {
		try {
			if (errors.hasErrors()) {
				return Result.errorAndMsg(errors.getFieldError().getDefaultMessage());
		    }
			Subject subject = SecurityUtils.getSubject();
			SysUser sysUser = (SysUser) subject.getPrincipal();
			Member member = dozerBeanMapper.map(memberVO,Member.class);
			member.setUpdateTime(new Date());
			member.setUpdateBy(sysUser.getLoginname());
			memberService.updateMember(member);
		} catch (UserMultipleException e){
			String message = messageSource.getMessage(ResultMsgEnum.USER_EXIST.getKey(),new Object[]{}, request.getLocale());
			logger.info(message,e.getMessage());
			return Result.error(ResultMsgEnum.USER_EXIST.code(),message);
		} catch (PhoneMultipleException e){
			String message = messageSource.getMessage(ResultMsgEnum.PHONE_MULTIPLE.getKey(),new Object[]{}, request.getLocale());
			logger.info(message,e.getMessage());
			return Result.error(ResultMsgEnum.CODE_MULTIPLE.code(),message);
		} catch (EmailMultipleException e){
			String message = messageSource.getMessage(ResultMsgEnum.EMAIL_MULTIPLE.getKey(),new Object[]{}, request.getLocale());
			logger.info(message,e.getMessage());
			return Result.error(ResultMsgEnum.CODE_MULTIPLE.code(),message);
		}  catch (Exception e) {
			String message = messageSource.getMessage(ResultMsgEnum.INTERNAL_SERVER_ERROR.getKey(),new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.error(ResultMsgEnum.INTERNAL_SERVER_ERROR.code(),message);
		}
		String message = messageSource.getMessage(ResultMsgEnum.SAVE_SUCCESS.getKey(),new Object[]{}, request.getLocale());
		return Result.success(ResultMsgEnum.SAVE_SUCCESS.code(),message);
	}

	/**
	 * 删除记录
	 */
	@ResponseBody
	@RequiresPermissions("oms:ucenter:member:delete")
	@RequestMapping(value="delete",method=RequestMethod.DELETE)
	@MethodName(value="系统管理->配置管理->服务器管理->删除",type=2)
	public Result delete(HttpServletRequest request, Long id) {
		try {
			if (id==null) {
				String message = messageSource.getMessage(ResultMsgEnum.PARAMETER_ERROR.getKey(),new Object[]{}, request.getLocale());
				logger.error(message);
				return Result.error(ResultMsgEnum.PARAMETER_ERROR.code(),message);
			}
			int deleteCount = memberService.deleteMember(id);
			if(deleteCount<=0){
				String message = messageSource.getMessage(ResultMsgEnum.DELETE_FAIL.getKey(),new Object[]{}, request.getLocale());
				logger.error(message);
				return Result.error(ResultMsgEnum.DELETE_FAIL.code(),message);
			}
		} catch(Exception e) {
			String message = messageSource.getMessage(ResultMsgEnum.INTERNAL_SERVER_ERROR.getKey(),new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.error(ResultMsgEnum.INTERNAL_SERVER_ERROR.code(),message);
		}
		String message = messageSource.getMessage(ResultMsgEnum.DELETE_SUCCESS.getKey(),new Object[]{}, request.getLocale());
		return Result.success(ResultMsgEnum.DELETE_SUCCESS.code(),message);

	}
	
}
